import {Component, OnInit} from '@angular/core';
import {Router, ActivatedRoute} from "@angular/router";
import {ResponseUtil} from "../../../../util/response-util";
import {PageSubject} from "../../../../util/page-subject";
import {OneDialogService} from "../../../../widgets/one-dialog/one-dialog.service";
import {AccountsService} from "../accounts.service";
import {MsgResult} from "../../../../models/msg-result";
import {Path} from "../../../../portal/admin/admin-breadcrumb/breadcrumb";
import {Role} from "../../roles/role";
import {MsgConstants} from "../../../../constants/constants";

declare var $;

@Component({
  selector: 'app-account-assign-role',
  templateUrl: './account-assign-role.component.html'
})
export class AccountAssignRoleComponent implements OnInit {

  /**
   * 声明路由id变量
   */
  accountId: string;

  /**
   * 定义id
   */
  roleId: string;

  /**
   * 声明实例
   */
  role: Role;

  /**
   * 声明变量
   */
  options: string;

  /**
   * 存储初始化遍历角色
   */
  roles: Role[];

  /**
   *
   * @type {Array}
   */
  roleIds: Array<string> = [];

  constructor(private router: Router,
              private route: ActivatedRoute,
              private responseUtil: ResponseUtil,
              private pageSubject: PageSubject,
              private dialogService: OneDialogService,
              private accountsService: AccountsService) {
    this.initObject();
  }

  ngOnInit() {
    //异步调用
    this.pushPage();
    if (!!this.route.snapshot.params["accountId"]) {
      //获取路由数据
      this.accountId = this.route.snapshot.params["accountId"];
      //获取账户数据进行初始化
      this.initRoleFormData();
    }
    if (!!this.route.snapshot.params["accoId"]) {
      //获取路由数据
      this.accountId = this.route.snapshot.params["accoId"];
      //获取账户数据进行初始化
      this.initRoleFormData();
    }
  }

  /**
   * 面包屑导航
   */
  private pushPage() {
    let path = new Path("权限系统", "");
    this.pageSubject.pushPage("账户管理", "分配角色", path);
  }

  /**
   * 初始化表单
   */
  initRoleFormData() {
    this.accountsService.getUndistributedRoleByAccId(this.accountId).subscribe(
      result => this.responseUtil.success(result, this.processRoleInitFormResult),
      message => this.responseUtil.error(message)
    );
  }

  /**
   * 截取初始化角色数据
   * @param result
   */
  private processRoleInitFormResult = (result: MsgResult) => {
    if (result && result.code == MsgConstants.MSG_CODE_OK) {
      for (let role of result.data) {
        $("#select_option_html").append("<option id=" + role.roleId + " value=" + role.roleId + ">" + role.roleName + "</option>");
      }
      this.getAssignedRole()
    }
    if (result && result.code != MsgConstants.MSG_CODE_OK) {
      this.dialogService.modalError(result.message);
    }
  }

  private getAssignedRole() {
    if (!!this.accountId) {
      this.accountsService.getAssignedRoleByAccId(this.accountId).subscribe(
        result => this.responseUtil.success(result, this.processAssignedRoleResult),
        message => this.responseUtil.error(message)
      );
    } else {
      this.dialogService.modalError("账户或角色为空！", () => this.cancelAssignRole());
    }
  }

  /**
   * 截取初始化角色数据
   * @param result
   */
  private processAssignedRoleResult = (result: MsgResult) => {
    if (result && result.code == MsgConstants.MSG_CODE_OK) {
      for (let role of result.data) {
        $("#select_option_html").append("<option id=" + role.roleId + " selected='selected' value=" + role.roleId + ">" + role.roleName + "</option>");
      }
      this.initAssigeRoleFoemData();
    }
    if (result && result.code != MsgConstants.MSG_CODE_OK) {
      this.dialogService.modalError(result.message);
    }
  }

  /**
   * 保存分配的角色
   */
  saveAssignRole() {
    if (!!this.accountId && !!this.roleIds) {
      this.accountsService.assignRoles(this.accountId, this.roleIds).subscribe(
        result => this.responseUtil.success(result, this.processAssignRoleResult),
        message => this.responseUtil.error(message)
      );
    } else {
      this.dialogService.modalError("账户或角色为空！", () => this.cancelAssignRole());
    }
  }

  /**
   * 处理分配角色数据
   * @param result
   */
  private processAssignRoleResult = (result: MsgResult) => {
    if (result && result.code == MsgConstants.MSG_CODE_OK) {
      this.dialogService.success("角色分配成功！", () => this.okAssignRole());
    }
    if (result && result.code != MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message);
    }
  }

  /**
   * 创建角色
   */
  accountCreateRole() {
    this.router.navigate(['../create', {accId: this.accountId}], {relativeTo: this.route});
  }

  /**
   * 上一步
   */
  cancelAssignRole() {
    this.router.navigate(['../add', {accId: this.accountId}], {relativeTo: this.route});
  }

  private okAssignRole() {
    this.router.navigate(['..'], {relativeTo: this.route});
  }


  /**
   * 实例化对象
   */
  private initObject() {
    this.role = new Role("", "", "", "", "", "", "");
  }


  initAssigeRoleFoemData() {

    //分配权限
    var demo2 = $('.demo1').bootstrapDualListbox({
      nonSelectedListLabel: '未分配角色',
      selectedListLabel: '已选择角色',
      preserveSelectionOnMove: 'moved',
      moveAllLabel: "移动所有",
      removeAllLabel: "移除所有",
      infoText: " ",
      infoTextEmpty: " ",
      filterPlaceHolder: "请输入要搜索的内容",
      moveOnSelect: true
    });

    /**
     *
     */
    $(".moveall").html('<i class="glyphicon glyphicon-chevron-right"></i><i class="glyphicon glyphicon-chevron-right"></i> ');

    $(".removeall").html('<i class="glyphicon glyphicon-chevron-left"></i><i class="glyphicon glyphicon-chevron-left"></i> ');
    /**
     *取消移除所有按钮
     */
    $(".one-duallistbox-container .btn-group").html("");

    /**
     *左侧列表框的右移
     */
    $("[name=roleName_helper1]").change(function () {
      this.options = $('#bootstrap-duallistbox-selected-list_roleName option').map(
        function (index, item) {
          return $(item).val();
        });
      this.roleIds = this.options.toArray();
    }.bind(this));

    /**
     *右侧列表框的左移
     */
    $("[name=roleName_helper2]").change(function () {
      this.options = $('#bootstrap-duallistbox-selected-list_roleName option').map(
        function (index, item) {
          return $(item).val();
        });
      this.roleIds = this.options.toArray();
    }.bind(this));
  }

}
